<template>
    <div>
        <!--  面包屑  -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--  卡片  -->
        <el-card>
            <!--      提示框区      -->
            <el-alert
                    show-icon
                    :closable="false"
                    title="注意: 只允许为第三级分类设置相关参数"
                    type="warning">
            </el-alert>
            <!--      搜索区      -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类:</span>
                    <el-cascader
                            expand-trigger="hover"
                            v-model="selectedCateKeys"
                            :props="cascaderProps"
                            change-on-select
                            @change="handleChange"
                            clearable
                            :options="setparamsList">
                    </el-cascader>
                </el-col>
            </el-row>
            <div style="height: 50px"></div>
            <!--      tab切换区      -->
            <el-row>
                <el-col>
                    <el-tabs v-model="activeName"
                             @tab-click="handleTabClick">
                        <el-tab-pane label="动态参数"
                                     name="many">
                            <el-button :disabled="isBtnDisabled"
                                       type="primary"
                                       @click="addDialogVisible = true"
                                       size="mini">
                                添加参数
                            </el-button>
                            <div style="height: 25px;"></div>
                            <!--            动态参数表格                -->
                            <el-table
                                    border
                                    stripe
                                    :data="manyTableData"
                                    style="width: 100%">
                                <el-table-column
                                        align="center"
                                        type="expand">
                                    <template slot-scope="scope">
                                        <el-tag v-for="(item,i) in scope.row.attr_vals"
                                                closable
                                                @close="handleClose(i,scope.row)"
                                                :key="i">
                                            {{item}}
                                        </el-tag>
                                        <el-input
                                                class="input-new-tag"
                                                v-if="scope.row.inputVisible"
                                                v-model="scope.row.inputValue"
                                                ref="saveTagInput"
                                                size="small"
                                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                                @blur="handleInputConfirm(scope.row)">
                                        </el-input>
                                        <el-button v-else
                                                   class="button-new-tag"
                                                   size="small"
                                                   @click="showInput(scope.row)">添加标签
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        label="#"
                                        align="center"
                                        type="index">
                                </el-table-column>
                                <el-table-column
                                        prop="attr_name"
                                        align="center"
                                        label="参数名称">
                                </el-table-column>
                                <el-table-column
                                        align="center"
                                        label="操作">
                                    <template slot-scope="scope">
                                        <!--      修改      -->
                                        <el-button type="primary"
                                                   @click="showEditDialog(scope.row.attr_id)"
                                                   icon="el-icon-edit"
                                                   size="small"></el-button>
                                        <!--      删除      -->
                                        <el-button type="danger"
                                                   @click="delDialog(scope.row.attr_id)"
                                                   icon="el-icon-delete"
                                                   size="small"></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="静态属性"
                                     name="only">
                            <el-button :disabled="isBtnDisabled"
                                       type="primary"
                                       @click="addDialogVisible = true"
                                       size="mini">
                                添加属性
                            </el-button>
                            <div style="height: 25px;"></div>
                            <!--            静态参数表格                -->
                            <el-table
                                    border
                                    stripe
                                    :data="onlyTableData"
                                    style="width: 100%">
                                <el-table-column
                                        align="center"
                                        type="expand">
                                    <template slot-scope="scope">
                                        <el-tag v-for="(item,i) in scope.row.attr_vals"
                                                closable
                                                @close="handleClose(i,scope.row)"
                                                :key="i">
                                            {{item}}
                                        </el-tag>
                                        <el-input
                                                class="input-new-tag"
                                                v-if="scope.row.inputVisible"
                                                v-model="scope.row.inputValue"
                                                ref="saveTagInput"
                                                size="small"
                                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                                @blur="handleInputConfirm(scope.row)">
                                        </el-input>
                                        <el-button v-else
                                                   class="button-new-tag"
                                                   size="small"
                                                   @click="showInput(scope.row)">添加标签
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        label="#"
                                        align="center"
                                        type="index">
                                </el-table-column>
                                <el-table-column
                                        prop="attr_name"
                                        align="center"
                                        label="属性名称">
                                </el-table-column>
                                <el-table-column
                                        align="center"
                                        label="操作">
                                    <template slot-scope="scope">
                                        <!--      修改      -->
                                        <el-button type="primary"
                                                   @click="showEditDialog(scope.row.attr_id)"
                                                   icon="el-icon-edit"
                                                   size="small"></el-button>
                                        <!--      删除      -->
                                        <el-button type="danger"
                                                   @click="delDialog(scope.row.attr_id)"
                                                   icon="el-icon-delete"
                                                   size="small"></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
            <!--      添加按钮      -->
            <!--      列表区      -->
        </el-card>
        <!--    添加参数/属性对话框    -->
        <el-dialog
                :title="'添加' + titleText"
                :visible.sync="addDialogVisible"
                @close="addDialogClosed"
                width="50%">
            <!--   主体区域   -->
            <el-form :model="addFrom"
                     :rules="addFromRoles"
                     ref="addFromRef"
                     label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!--   按钮区域   -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary"
                           @click="setAddFromDialog">确 定</el-button>
            </span>
        </el-dialog>
        <!--    表格修改对话框    -->
        <el-dialog
                :title="'修改' + titleText"
                :visible.sync="updateDialogVisible"
                @close="updateDialogClosed"
                width="50%">
            <!--   主体区域   -->
            <el-form :model="updateFrom"
                     :rules="updateFromRoles"
                     ref="updateFromRef"
                     label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="updateFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!--   按钮区域   -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateDialogVisible = false">取 消</el-button>
                <el-button type="primary"
                           @click="setupdateFromDialog">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        // 分类数据
        setparamsList: [],
        // 级联配置
        cascaderProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 选中级联数据
        selectedCateKeys: [],
        // 切换tabs
        activeName: 'many',
        // 动态参数表格数据
        manyTableData: [],
        // 静态参数表格数据
        onlyTableData: [],
        // 对话框
        addDialogVisible: false,
        // 表单数据
        addFrom: {
          attr_name: ''
        },
        // 校验
        addFromRoles: {
          attr_name: [
            {
              required: true, message: '请输入参数', trigger: 'blur'
            }
          ]
        },
        // 表格修改对话框
        updateDialogVisible: false,
        updateFrom: {
          attr_name: ''
        },
        updateFromRoles: {
          attr_name: [
            {
              required: true, message: '请输入参数', trigger: 'blur'
            }
          ]
        }
      }
    },
    mounted() {
      this.getCategories()
    },
    methods: {
      // 分类请求
      getCategories() {
        this.$http.get('categories').then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.setparamsList = res.data.data
        })
      },
      // 监听级联选择框
      handleChange() {
        // 请求分类
        this.getParamsData()
      },
      // tab点击事件
      handleTabClick() {
        console.log(this.activeName)
        // 请求分类
        this.getParamsData()
      },
      // 分类请求函数
      getParamsData() {
        // 不是三级分类
        if (this.selectedCateKeys.length !== 3) {
          this.selectedCateKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        // 是三级分类
        console.log(this.selectedCateKeys)
        // 分类请求
        this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          // 获取返回数据
          // 数据循环
          // 判断为空
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            // 控制文本的显示与隐藏
            item.inputVisible = false
            // 文本输入的值
            item.inputValue = ''
          })
          // 判断数据分配
          if (this.activeName === 'many') {
            this.manyTableData = res.data.data
          } else {
            this.onlyTableData = res.data.data
          }
        })
      },
      // 监听对话框
      addDialogClosed() {
        // 重置
        this.$refs.addFromRef.resetFields()
      },
      // 添加表单
      setAddFromDialog() {
        this.$refs.addFromRef.validate(valid => {
          if (!valid) return
          this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addFrom.attr_name,
            attr_sel: this.activeName
          }).then(res => {
            if (res.data.meta.status !== 201) {
              return this.$message.error(res.data.meta.msg)
            }
            this.$message.success(res.data.meta.msg)
            this.addDialogVisible = false
            this.getParamsData()
          })
        })
      },
      // 表格修改对话框
      showEditDialog(attr_id) {
        this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
          params: {attr_sel: this.activeName}
        }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.updateFrom = res.data.data
          this.updateDialogVisible = true
        })
      },
      // 修改按钮
      setupdateFromDialog() {
        this.$refs.updateFromRef.validate(valid => {
          if (!valid) return
          this.$http.put(`categories/${this.cateId}/attributes/${this.updateFrom.attr_id}`, {
            attr_name: this.updateFrom.attr_name,
            attr_sel: this.activeName
          }).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error(res.data.meta.msg)
            }
            this.$message.success(res.data.meta.msg)
            this.updateDialogVisible = false
            this.getParamsData()
          })
        })
      },
      // 重置
      updateDialogClosed() {
        this.$refs.updateFromRef.resetFields()
      },
      // 删除
      delDialog(id) {
        this.$alert('确定删除吗', '删除参数', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          this.$http.delete(`categories/${this.cateId}/attributes/${id}`).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error(res.data.meta.msg)
            }
            this.$message.success(res.data.meta.msg)
            this.getParamsData()
          })
        }).catch(err => err)
      },
      // 删除标签
      handleClose(i, row) {
        row.attr_vals.splice(i, 1);
        this.addTags(row)
      },
      // 添加标签
      showInput(row) {
        row.inputVisible = true;
        // 文本框自动获得焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 标签输入框 带快捷键
      handleInputConfirm(row) {
        // 判断不合法数据
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        // 此处文本框数据需要处理
        // 添加
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        // 请求保存数据库
        this.addTags(row)
      },
      // 保存标签
      addTags(row) {
        this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
        })
      }
    },
    computed: {
      // 计算属性
      // 如果按钮要禁用 则返回true 否则　false
      isBtnDisabled() {
        if (this.selectedCateKeys.length !== 3) {
          return true
        }
        return false
      },
      // 当前选中id的最后一个
      cateId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2]
        }
        return null
      },
      // 对话框
      titleText() {
        if (this.activeName === 'many') {
          return '动态参数'
        } else {
          return '静态属性'
        }
      }
    }
  }
</script>

<style lang="less" scoped>
    .cat_opt {
        margin: 25px 0;
        float: left;
    }

    .el-col {
        display: flex;
        line-height: 36px;
    }

    .el-col span {
        width: 150px;
    }

    .el-cascader {
        margin-left: 10px;
    }

    .el-tabs {
        width: 100%;
    }

    .el-tab-pane {
        float: left;
    }

    .el-table {
        width: 100%;
    }

    .el-button {
        float: left;
    }

    .el-tab-pane {
        width: 100%;
    }

    .el-tag {
        margin: 10px;
    }

    .el-col span[data-v-f56922dc] {
        width: 180px;
    }
</style>
